/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : my_mileage.js                            
*  Description  : 마일리지
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-07-06  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	// 마일리지
	function clsMileage()
	{
		this._HTMLDom = null;
		this.infoData = null;
		
		this._init();
	}
	
	clsMileage.prototype = {
		_init: function(){
			var $layer = $("div#container div.my_mileage_box");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setInfo({
				"마일리지": 0
				, "닉네임": ""
			});
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setInfo: function(thisData){
			this.infoData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			
			var m = _util.number_format(this.infoData["마일리지"]);
			
			var sm = "";
			for(var i=0;i<m.length;i++){
				switch(m.charAt(i)){
					case ",":
						sm += '<span class="dot">,</span>';
						break;
					default:
						sm += '<span class="num' + m.charAt(i) + '">' + m.charAt(i) + '</span>';
						break;
				}
			}
			
			$layer.find("p.name").html(this.infoData["닉네임"]);
			$layer.find("p.money ").html(sm +'<em class="txt_won">M</em>');
		}
	}
	
	// 검색
	function clsSearch()
	{
		this._HTMLDom = null;
		this.idx;
		this._monthList = null;
		
		this._init();
	}
	
	clsSearch.prototype = {
		_init: function(){
			var $layer = $("div#container dl.score_search");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this._monthList = [
				1, 3, 6, 12
			]
			
			$layer.find("img[alt='달력']").hide();
			
			$layer.find("input:text").attr({
				"readonly": "readonly"
			}).datepicker({
				showOn: "both"
				, buttonImage: $layer.find("img[alt='달력']").attr("src")
				, buttonImageOnly: true
			});
			
			var t = new Date();
			
			$layer.find("input:text").val(t.getFullYear() + "-" + ("00" + (t.getMonth()+1)).substrEx(-2) + "-" + ("00" + t.getDate()).substrEx(-2));
			
			this.setIdx(0);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setIdx: function(n){
			this.idx = n;
			this.display();
		}
		, display: function(){
			var $layer = this.$getLayer();
			
			$layer.find("a img:not([alt='달력'])").each(function(){
				var src = $(this).attr("src");
				$(this).attr("src", src.replace("_on", ""));
			});
			
			var src = $layer.find("a img:not([alt='달력'])").eq(this.idx).attr("src");
			$layer.find("a img:not([alt='달력'])").eq(this.idx).attr("src", src.replace(".gif", "_on.gif"));
		}
		, getDateValue: function(){
			var $layer = this.$getLayer();
			
			return $layer.find("input:text").val().replace(/-/gi, "");
		}
		, getPeriodValue: function(){
			return this._monthList[this.idx];
		}
	}
	
	// 적립마일리지 리스트
	function clsSavedMileageList()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsSavedMileageList.prototype = {
		_init: function(){
			var $layer = $("div#container article.list01");
			this._HTMLDom = {
				"$layer": $layer
				, "$element": $layer.find("tbody tr:first").clone(true)
			}
			
			this.setList([]);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = thisData;
			this.display();
		}
		, display: function(){
			var $layer = this.$getLayer();
			var $element = this._HTMLDom["$element"];
			var thisClass = this;
			
			$layer.find("tbody").empty();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("tbody").append($element.clone(true));
			}
			$layer.find("tbody tr").each(function(n){
				var d = thisClass.listData[n];
				
				$(this).find("td:eq(0)").html(d["거래일자"]);
				$(this).find("td:eq(1) strong").html(d["구분"]);
				$(this).find("td:eq(2)").html(d["결재금액"]);
				$(this).find("td:eq(3)").html(d["골프장명"]);
				$(this).find("td:eq(4)").html(d["상태"]);
				$(this).find("td:eq(5)").html(d["적립마일리지"]);
				$(this).find("td:eq(6)").html("-");
				$(this).find("td:eq(7)").html(d["사용처"]);
			});
		}
		, spinStart: function(){
			var $layer = this.$getLayer();
			
			$layer.find("tbody").hide();
			if($layer.find("div#tmpSpin").length == 0){
				$layer.append("<div id='tmpSpin' style='position:relative: width:700px; height:100px;' />");
			}
			$layer.find("div#tmpSpin").show().spin();
		}
		, spinEnd: function(){
			var $layer = this.$getLayer();
			
			$layer.find("tbody").show();
			$layer.find("div#tmpSpin").hide().spin(false);
		}
	}

	// 서버통신
	function clsComm()
	{
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){

		}
		// 보유마일리지
		, getMileage: function(){
			var thisClass = this;
			
			//ajax
			var serviceName = "getMyPoint";
			var options = {
				
			}
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "결과값": {}
				}
				
				var items =  ret["msp"]["contents"]["items"];
				
				if(items == 0 || items){
					res["결과값"] = {
						"마일리지": items
					}
				}
				
				document.objControl.finishMileage(res);
			});
		}
		// 적립 마일리지 리스트
		, getSavedMileageList: function(arg){
			var thisClass = this;
			
			//ajax
			var serviceName = "getUserMyPayList";
			var options = {
				"searchStartDate": arg["날짜"]
				, "searchTerm": arg["기간"]
			}
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "전체수": ret["msp"]["contents"]["@totalcount"]
					, "결과값": []
				}
				
				var items =  ret["msp"]["contents"]["items"];
				if(items){
					if(!items.length) items = new Array(items);
					for(var i=0;i<items.length;i++){
						var obj = items[i];
						
						
//						$(this).find("td:eq(0)").html(d["거래일자"]);
//				$(this).find("td:eq(1) strong").html(d["구분"]);
//				$(this).find("td:eq(2)").html(d["결재금액"]);
//				$(this).find("td:eq(3)").html(d["골프장명"]);
//				$(this).find("td:eq(4)").html(d["상태"]);
//				$(this).find("td:eq(5)").html(d["적립마일리지"]);
//				$(this).find("td:eq(6)").html("-");
//				$(this).find("td:eq(7)").html(d["사용처"]);
						
						res["결과값"].push({
							"거래일자": _util.nvl(obj["regDate"])
							, "구분": _util.nvl(obj["mileageType"])
							, "결재금액": _util.nvl(obj["payAmt"])
							, "골프장명": _util.nvl(obj["goodName"])
							, "상태": _util.nvl(obj["rounding"])
							, "적립마일리지": _util.nvl(obj["mileageAmount"])
						});
					}
				}
				
				document.objControl.finishSavedMileageList(res);
			});
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objMileage = null;
		this.objSearch = null;
		this.objSavedMileageList = null;
		this.objSavedMileagePaging = null;
		
		this._permitStart = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objMileage = new clsMileage();
			this.objSearch = new clsSearch();
			this.objSavedMileageList = new clsSavedMileageList();
			this.objSavedMileagePaging = new _gf.makePaging($("div#idSavedMileagePaging"), 10, 10);
			
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
			
			var $p = $("div#container ul.pagenum_area");
			
			$p.wrap("<div id='idSavedMileagePaging' />");
			$p.remove();
		}
		, _beforeStart: function(){
			var thisClass = this;
			
			this._permitStart = {
				
			}
			
			
			$.ajax({
				url: _ROOT + "/js/mypage_common.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				for(key in thisClass._permitStart){
					if(!thisClass._permitStart[key]) return false;
				}
				
				return (_gf.getMyInfoData());
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			this.objSearch.$getLayer().on("click", "a img:not([alt='달력'])", function(){
				var n = thisClass.objSearch.$getLayer().find("a img:not([alt='달력'])").index($(this));
				thisClass.objSearch.setIdx(n);
				
				// 적립마일리지
				thisClass.getSavedMileageList();
			});
		}
		, _start: function(){
			// 보유마일리지
			this.objComm.getMileage();
			// 적립마일리지 리스트
			this.getSavedMileageList();
		}
		// 적립마일리지 리스트
		, getSavedMileageList: function(){
			this.objSavedMileageList.spinStart();
			this.objComm.getSavedMileageList({
				"날짜": this.objSearch.getDateValue()
				, "기간": this.objSearch.getPeriodValue()
			});
		}
		// 보유마일리지 완료
		, finishMileage: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var myInfo = _gf.getMyInfoData();
			
			ret["결과값"]["닉네임"] = myInfo["닉네임"];
			
			this.objMileage.setInfo(ret["결과값"]);
		}
		// 적립 마일리지 리스트 완료
		, finishSavedMileageList: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			this.objSavedMileageList.spinEnd();
			this.objSavedMileageList.setList(ret["결과값"]);
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});